{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>示例1：直接通过秘钥进行上传文件</h1>
<input type="file" name="upload_file" id="uploadFile" multiple/>

<script src="{% static 'app01/js/jquery-3.6.0.min.js' %} "></script>
<script src="{% static 'app01/js/baidubce-sdk.bundle.min.js' %}"></script>

<script>
    let client;
    $(function () {
        initBOS();
        bindUpload();
    })

    function initBOS() {
        $.ajax({
            url: '{% url "app01:bos_credential" %}',
            type: 'GET',
            dataType: 'JSON', // 将服务器返回的数据反序列化成字典
            success: function (res) {
                client = new baidubce.sdk.BosClient({
                    credentials: {
                        ak: res.bosConfig.credentials.ak, // STS服务器下发的临时ak
                        sk: res.bosConfig.credentials.sk, // STS服务器下发的临时sk
                    },
                    sessionToken: res.bosConfig.sessionToken,  // STS服务器下发的sessionToken
                    endpoint: res.bosConfig.endpoint,
                });
            }
        })
    }

    let bucket = 'bucket-baiduyun';

    function bindUpload() {
        $('#uploadFile').on('change', function (evt) {
            var files = evt.target.files; // 获取要上传的文件
            console.log(files, 5555);
            $.each(files, function (index, file) {
                var key = file.name; // 保存到bos时的key，您可更改，默认以文件名作为key
                var blob = file;

                var ext = key.split(/\./g).pop();
                var mimeType = baidubce.sdk.MimeType.guess(ext);
                if (/^text\//.test(mimeType)) {
                    mimeType += '; charset=UTF-8';
                }
                var options = {
                    'Content-Type': mimeType
                };

                client.putObjectFromBlob(bucket, key, blob, options)
                    .then(function (res) {
                        // 上传完成，添加您的代码
                        console.log('上传成功');
                    })
                    .catch(function (err) {
                        // 上传失败，添加您的代码
                        {#console.error(err);#}
                        console.log(err);
                    });
            })
        });

    }
</script>

</body>
</html>